import React, { useEffect, useState } from 'react'
import { Button, notification, Table, Tag } from 'antd'
import { useNavigate } from 'react-router'
import { getNewsListApi, updateNewsApi } from '@/api/news'

function AuditList() {
  const navigate = useNavigate()
  const { username } = JSON.parse(localStorage.getItem('token'))
  const [dataSource, setDataSource] = useState([])
  const [listLoading, setListLoading] = useState(false)

  useEffect(() => {
    getNewsList()
  }, [username])

  // 获取列表
  const getNewsList = () => {
    setListLoading(true)
    getNewsListApi({
      author: username,
      auditState_ne: 0,
      publishState_lte: 1,
      '_expand': 'category'
    }).then(res => {
      setListLoading(false)
      setDataSource(res)
    })
  }

  // 撤销
  const handleCancel = (item) => {
    updateNewsApi(item.id, {
      ...item,
      auditState: 0
    }).then(() => {
      // 跳转到草稿列表
      navigate('/news-manage/draft')
      // 通知用户
      notification.info({
        message: '通知',
        description: '您可以到草稿箱中查看新闻',
        placement: 'bottomRight'
      })
    })
  }

  // 修改
  const handleUpdate = (item) => {
    navigate(`/news-manage/update/${item.id}`)
  }

  // 发布
  const handleRelease = (item) => {
    updateNewsApi(item.id, {
      ...item,
      publishState: 2,
      publishTime: Date.now()
    }).then(() => {
      // 跳转到已发布列表
      navigate('/publish-manage/published')
      // 通知用户
      notification.info({
        message: '通知',
        description: '您可以到发布管理/已发布中查看新闻',
        placement: 'bottomRight'
      })
    })
  }

  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, item) => {
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'author'
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return category.value
      }
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      render: (auditState) => {
        const colorList = ['', 'orange', 'green', 'red']
        const auditList = ['草稿箱', '审核中', '已通过', '未通过']
        return <Tag color={colorList[auditState]}>{auditList[auditState]}</Tag>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          {
            item.auditState === 1 && <Button onClick={() => handleCancel(item)}>撤销</Button>
          }
          {
            item.auditState === 2 && <Button danger onClick={() => handleRelease(item)}>发布</Button>
          }
          {
            item.auditState === 3 && <Button onClick={() => handleUpdate(item)} type={'primary'}>修改</Button>
          }
        </div>

      }
    }
  ]

  return (
    <div>
      <Table
        columns={columns}
        dataSource={dataSource}
        loading={listLoading}
        pagination={{ pageSize: 5 }}
        rowKey={item => item.id}
      />
    </div>
  )
}

export default AuditList